//
//  KcSelectImageTool.swift
//  KcSwiftDemo
//
//  Created by 张杰 on 2017/8/24.
//  Copyright © 2017年 张杰. All rights reserved.
//  选择图片

import UIKit
import AVFoundation
import AssetsLibrary
import TZImagePickerController

public class KcSelectImageTool: NSObject {
    
    public weak var viewController: UIViewController?
    private let maxImagesCount: Int
    
    public init(_ viewController: UIViewController, maxImagesCount: Int) {
        self.viewController = viewController
        self.maxImagesCount = maxImagesCount
        super.init()
    }
    
    public func show(_ optionalCount: Int, finishBlock: @escaping (_ photos: [UIImage]?)->Void) {
        //1.判断权限
        let author = ALAssetsLibrary.authorizationStatus()
        if (author == .restricted || author == .denied) {
            showMessage(false)
            return
        }
        
        let imagePickerVc = TZImagePickerController(maxImagesCount: maxImagesCount, delegate: self)
        
        imagePickerVc?.isSelectOriginalPhoto = false
        imagePickerVc?.allowPickingVideo = false
        imagePickerVc?.allowPickingImage = true
        imagePickerVc?.allowPickingOriginalPhoto = false
        imagePickerVc?.allowTakePicture = false
        //可选的个数
        imagePickerVc?.maxImagesCount = optionalCount
        // 4. 照片排列按修改时间升序
        imagePickerVc?.sortAscendingByModificationDate = true
        imagePickerVc?.oKButtonTitleColorNormal = UIColor.blue
        imagePickerVc?.oKButtonTitleColorDisabled = UIColor.blue
        
        // You can get the photos by block, the same as by delegate.
        // 你可以通过block或者代理，来得到用户选择的照片.
        imagePickerVc?.didFinishPickingPhotosHandle = { (photos: [UIImage]?, assets: [Any]?, isSelectOriginalPhoto: Bool) in
            finishBlock(photos)
        }
        viewController!.present(imagePickerVc!, animated: true, completion: nil)
    }
}

extension KcSelectImageTool {
    fileprivate func showMessage(_ isCamera: Bool = true) {
        let appCurName = getBundleName()
        let title = isCamera ? "相机" : "相册"
        let alert = UIAlertView(title: nil, message: "请在iPhone的“设置-隐私-\(title)”选项中，允许\(appCurName)访问你的\(title)", delegate: self, cancelButtonTitle: "好")
        alert.show()
    }
    
    //MARK: 获取工程的名字
    private func getBundleName() -> String{
        let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String  //这里也是坑，请不要翻译oc的代码，而是去NSBundle类里面看它的api
        return appName!
        //        var bundlePath = Bundle.main.bundlePath
        //        bundlePath = bundlePath.components(separatedBy: "/").last!
        //        bundlePath = bundlePath.components(separatedBy: ".").first!
        //        return bundlePath
    }
}

extension KcSelectImageTool : TZImagePickerControllerDelegate {
    
}
